<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript,浏览器,数据存储," />










<meta name="description" content="前言：五一假期在撸代码的时候用到cookie，感觉对浏览器的数据存储方案不是很了解，因此又去翻了两本大头书中间的关于浏览器端数据存储的章节，同时去MDN逛了逛，又看了几篇文章，算是对浏览器的数据存储方案有了一个了解，在此总结一下！ 浏览器存储在浏览器端存储数据对我们是很有用，这相当于赋予浏览器记忆的功能，可以纪录用户的所有状态信息，增强用户体验。比如当纪录用户的登陆状态时，可以让用户能够更快的进行">
<meta name="keywords" content="JavaScript,浏览器,数据存储">
<meta property="og:type" content="article">
<meta property="og:title" content="聊一聊常见的浏览器端数据存储方案">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/05/06/聊一聊常见的浏览器端数据存储方案/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="前言：五一假期在撸代码的时候用到cookie，感觉对浏览器的数据存储方案不是很了解，因此又去翻了两本大头书中间的关于浏览器端数据存储的章节，同时去MDN逛了逛，又看了几篇文章，算是对浏览器的数据存储方案有了一个了解，在此总结一下！ 浏览器存储在浏览器端存储数据对我们是很有用，这相当于赋予浏览器记忆的功能，可以纪录用户的所有状态信息，增强用户体验。比如当纪录用户的登陆状态时，可以让用户能够更快的进行">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/5/3/16325ce01e799f9f?w=749&h=356&f=png&s=111928">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/5/3/16325ce02ccb3e88?w=1240&h=189&f=png&s=58377">
<meta property="og:updated_time" content="2018-07-11T02:15:25.581Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="聊一聊常见的浏览器端数据存储方案">
<meta name="twitter:description" content="前言：五一假期在撸代码的时候用到cookie，感觉对浏览器的数据存储方案不是很了解，因此又去翻了两本大头书中间的关于浏览器端数据存储的章节，同时去MDN逛了逛，又看了几篇文章，算是对浏览器的数据存储方案有了一个了解，在此总结一下！ 浏览器存储在浏览器端存储数据对我们是很有用，这相当于赋予浏览器记忆的功能，可以纪录用户的所有状态信息，增强用户体验。比如当纪录用户的登陆状态时，可以让用户能够更快的进行">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/5/3/16325ce01e799f9f?w=749&h=356&f=png&s=111928">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/05/06/聊一聊常见的浏览器端数据存储方案/"/>





  <title>聊一聊常见的浏览器端数据存储方案 | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/06/聊一聊常见的浏览器端数据存储方案/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">聊一聊常见的浏览器端数据存储方案</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-06T13:46:54+08:00">
                2018-05-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/浏览器/" itemprop="url" rel="index">
                    <span itemprop="name">浏览器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,553
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  14
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="前言："><a href="#前言：" class="headerlink" title="前言："></a>前言：</h3><p>五一假期在撸代码的时候用到cookie，感觉对浏览器的数据存储方案不是很了解，因此又去翻了两本大头书中间的关于浏览器端数据存储的章节，同时去MDN逛了逛，又看了几篇文章，算是对浏览器的数据存储方案有了一个了解，在此总结一下！</p>
<h2 id="浏览器存储"><a href="#浏览器存储" class="headerlink" title="浏览器存储"></a>浏览器存储</h2><p>在浏览器端存储数据对我们是很有用，这相当于赋予浏览器记忆的功能，可以纪录用户的所有状态信息，增强用户体验。比如当纪录用户的登陆状态时，可以让用户能够更快的进行访问，而不是每次登陆时都需要去进行繁琐的操作。</p>
<p>总的来说,现在市面上最常见的数据存储方案是以下三种：</p>
<ul>
<li>Cookie</li>
<li>web存储 (locaStorage和seesionStorage)</li>
<li>IndexedDB</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2018/5/3/16325ce01e799f9f?w=749&amp;h=356&amp;f=png&amp;s=111928" alt="图片.png"></p>
<h2 id="Cookie"><a href="#Cookie" class="headerlink" title="Cookie"></a>Cookie</h2><p>Cookie的又称是HTTP Cookie，最初是在客户端用于存储会话信息，从底层来看，它作为HTTP协议的一种扩展实现，Cookie数据会自动在web浏览器和web服务器之间传输，因此在服务器端脚本就可以读写存储的cookie的值。Cookie通常用于存储一些通用的数据，比如用户的登陆状态，首选项等。虽然随着时代的进步，HTML5所提供的web存储机制已经逐步替代了Cookie，但有些较为老的浏览器还是不兼容web存储机制，此外在用户认证方面，cookie+session还是当今的主流，也非常好用。因此正处于这个老旧更替阶段的我们对于它还是要学习学习的。</p>
<h3 id="Cookie的优点"><a href="#Cookie的优点" class="headerlink" title="Cookie的优点"></a>Cookie的优点</h3><p>首先由于操作Cookie的API很早就已经定义和实现了，因此相比于其他的数据存储方式，Cookie的兼容性非常的好，兼容现在市面上所有的主流浏览器，我们在使用它的时候完全不用担心兼容问题。</p>
<h3 id="Cookie的缺点"><a href="#Cookie的缺点" class="headerlink" title="Cookie的缺点"></a>Cookie的缺点</h3><p>说到Cookie的缺点，那就有点多了，不然也不会在Cookie后面出现web存储等新的数据存储的方案了。<br>总结起来Cookie的缺点主要是以下几点：</p>
<ol>
<li>存储量小。虽不同浏览器的存储量不同，但基本上都是在4kb左右。</li>
<li>影响性能。由于Cookie会由浏览器作为请求头发送，因此当Cookie存储信息过多时，会影响特定域的资源获取的效率，增加文档传输的负载。</li>
<li>只能储存字符串。</li>
<li>安全问题。存储在Cookie的任何数据可以被他人访问，因此不能在Cookie中储存重要的信息。</li>
<li>由于第三方Cookie的滥用，所以很多老司机在浏览网页时会禁用Cookie，所以我们不得不测试用户是否支持Cookie，这也是很麻烦的一件事。<h3 id="Cookie的操作"><a href="#Cookie的操作" class="headerlink" title="Cookie的操作"></a>Cookie的操作</h3>基本的Cookie操作主要有三个：读取，写入和删除。但在 JavaScript 中去处理 cookie 是一件很繁琐的事情，因为 cookie 中的所有的名字和值都是经过URI编码的，所以当我们必须使用 decodeURICompoent 来进行解码才能得到 cookie 的值。我们来看看 CookieUtil 对象是如何操纵 cookie 的：</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> CookieUtil = &#123;</span><br><span class="line">	<span class="comment">// get可根据cookie的名字获取相应的值</span></span><br><span class="line">	get: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">const</span> cookieName = encodeURIcOMPONET(name) + <span class="string">"="</span>,</span><br><span class="line">			   cookieStart = <span class="built_in">document</span>.cookie.indexOf(cookieName),</span><br><span class="line">			   cookieValue = <span class="literal">null</span></span><br><span class="line">		<span class="keyword">if</span>(cookieStart &gt; <span class="number">-1</span>) &#123;</span><br><span class="line">			<span class="keyword">const</span> cookieEnd = <span class="built_in">document</span>.cookie.indexOf(<span class="string">";"</span>, cookieStart)</span><br><span class="line">			<span class="keyword">if</span>(cookieEnd == <span class="number">-1</span>) &#123;</span><br><span class="line">				cookieEnd = <span class="built_in">document</span>.cookie.length</span><br><span class="line">			&#125;</span><br><span class="line">			cookieValue = decodeURICompoent(<span class="built_in">document</span>.cookie.substring(cookieStart + cookieName.length, cookieEnd))	</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> cookieValue</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// set设置一个cookie</span></span><br><span class="line">	set: <span class="function"><span class="keyword">function</span>(<span class="params">name, value, expires, path, domain, secure</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">var</span> cookieText = encodeURIComponet(name)+<span class="string">"="</span>+encodeURIComponet(value)</span><br><span class="line">		<span class="keyword">if</span>(expires <span class="keyword">instanceof</span> <span class="built_in">Date</span>) &#123;</span><br><span class="line">			cookieText += <span class="string">"; expires="</span> + expires.toGMTString()</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span>(path) &#123;</span><br><span class="line">			cookieText += <span class="string">";path="</span> + path</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span>(domain) &#123;</span><br><span class="line">			cookieText += <span class="string">"; domain"</span> + domain</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span>(secure) &#123;</span><br><span class="line">			cookieText += <span class="string">"; secure"</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">document</span>.cookie = cookieText</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 删除已有的cookie</span></span><br><span class="line">	unset: <span class="function"><span class="keyword">function</span>(<span class="params">name, path, domain, secure</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.set(name, <span class="string">""</span>, <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">0</span>), path, domain, secure)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>是不是很麻烦，无论是获取一个cookie的值或是设置一个cookie都是很麻烦的事情，这也成为了后续的浏览器数据存储方案出现的一大原因。</p>
<h2 id="web存储"><a href="#web存储" class="headerlink" title="web存储"></a>web存储</h2><p>web存储机制最初作为HTML5的一部分被定义成API的形式，但又由于其本身的独特性与其他的一些原因而剥离了出来，成为独立的一个标准。web存储标准的API包括localStorage对象和seesionStorage对象。它所产生的主要原因主要出于以下两个原因：</p>
<ul>
<li>人们希望有一种在cookie之外存储回话数据的途径。</li>
<li>人们希望有一种存储大量可以跨会话存在的数据的机制。</li>
</ul>
<p>（注：其实在最初的web存储规范中包含了两种对象的定义：seesionStorage和globalStorage,这两个对象在支持这两个对象的浏览器中都是以windows对象属性的形式存在的）</p>
<h3 id="locaStorage"><a href="#locaStorage" class="headerlink" title="locaStorage"></a>locaStorage</h3><p>localStorage对象在修订过的HTML5规范中作为持久保存客户端数据的方案取代了我们上面所提到的globalStorage。从功能上来讲，我们可以通过locaStorage在浏览器端存储键值对数据，它相比于cookie而言，提供了更为直观的API，且在安全上相对好一点<br>，而且虽然localStorage只能存储字符串，但它也可以存储字符串化的JSON数据，因此相比于cookie，localStorage能存储更复杂的数据。总的来说相较于cookie，localStorage有以下优势：</p>
<ul>
<li>提供了简单明了的API来进行操作</li>
<li>更加安全</li>
<li>可储存的数据量更大</li>
</ul>
<p>也正是出于以上这些原因，localStorage被视为替代cookie的解决方案，但还是要注意不要在localStorage中存储敏感信息。</p>
<h4 id="localStorage的基本语法"><a href="#localStorage的基本语法" class="headerlink" title="localStorage的基本语法"></a>localStorage的基本语法</h4><p>localStorage的基本操作很简单，示例如下：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用方法存储数据</span></span><br><span class="line">localStorage.setItem(<span class="string">"name"</span>, <span class="string">"Srtian"</span>)</span><br><span class="line"><span class="comment">// 使用属性存储数据</span></span><br><span class="line">localStorage.say = <span class="string">"Hello world"</span></span><br><span class="line"><span class="comment">// 使用方法读取数据</span></span><br><span class="line"><span class="keyword">const</span> name = localStorage.getItem(<span class="string">"name"</span>)</span><br><span class="line"><span class="comment">// 使用属性读取数据</span></span><br><span class="line"><span class="keyword">const</span> say = localStorage.say</span><br><span class="line"><span class="comment">// 删除数据</span></span><br><span class="line">localStorage.removeItem(<span class="string">"name"</span>)</span><br></pre></td></tr></table></figure></p>
<p>但需要注意的是，我们上面的示例全是存储字符串格式的数据，当我们需要传输其他格式的数据时，我们就需要将这些数据全部转换为字符串格式，然后再进行存储：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> user = &#123;<span class="attr">name</span>:<span class="string">"Srtian"</span>, <span class="attr">age</span>: <span class="number">22</span>&#125;</span><br><span class="line">localStorage.setItem(<span class="string">"user"</span>, <span class="built_in">JSON</span>.stringify(user))</span><br></pre></td></tr></table></figure>
<p>当然，我们在获取值的时候也别忘了将其转化回来：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> age = <span class="built_in">JSON</span>.parse(localStorage.user)</span><br></pre></td></tr></table></figure>
<h4 id="localStorage储存数据的有效期与作用域"><a href="#localStorage储存数据的有效期与作用域" class="headerlink" title="localStorage储存数据的有效期与作用域"></a>localStorage储存数据的有效期与作用域</h4><p>通过locaStorage存储的数据时永久性的，除非我们使用removeItem来删除或者用户通过设置浏览器配置来删除，负责数据会一直保留在用户的电脑上，永不过期。</p>
<p>localStorage的作用域限定在文档源级别的（意思就是同源的才能共享），同源的文档间会共享localStorage的数据，他们可以互相读取对方的数据，甚至有时会覆盖对方的数据。当然，localStorage的作用域同样也受浏览器的限制。</p>
<h4 id="localStorage的兼容"><a href="#localStorage的兼容" class="headerlink" title="localStorage的兼容"></a>localStorage的兼容</h4><p>locaStorage的兼容如下表所示：</p>
<pre><code>    Feature     Chrome     Edge     Firefox (Gecko) Internet Explorer     Opera     Safari (WebKit)
localStorage     4     (Yes)        3.5                 8                  10.50     4
sessionStorage     5     (Yes)        2                 8                  10.50        4
</code></pre><h3 id="sessionStorage"><a href="#sessionStorage" class="headerlink" title="sessionStorage"></a>sessionStorage</h3><p>sessionStorage是web存储机制的另一大对象，sessionStorage 属性允许我们去访问一个 session Storage 对象。它与 localStorage 相似，不同之处在于 localStorage里面存储的数据没有过期时间设置，而Session Storage只存储当前会话页的数据，且只有当用户关闭当前会话页或浏览器时，数据才会被清除。</p>
<h4 id="sessionStorage的基本语法"><a href="#sessionStorage的基本语法" class="headerlink" title="sessionStorage的基本语法"></a>sessionStorage的基本语法</h4><p>我们可以通过下面的语法，来保存，获取，删除数据，大体语法与：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 保存数据到sessionStorage</span></span><br><span class="line">sessionStorage.setItem(<span class="string">'name'</span>, <span class="string">'Srtian'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 从sessionStorage获取数据</span></span><br><span class="line"><span class="keyword">var</span> data = sessionStorage.getItem(<span class="string">'name'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 从sessionStorage删除保存的数据</span></span><br><span class="line">sessionStorage.removeItem(<span class="string">'name'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 从sessionStorage删除所有保存的数据</span></span><br><span class="line">sessionStorage.clear();</span><br></pre></td></tr></table></figure></p>
<p>下面的示例会自动保存一个文本输入框的内容，如果浏览器因偶然因素被刷新了，文本输入框里面的内容会被恢复，写入的内容不会丢失：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取文本输入框</span></span><br><span class="line"><span class="keyword">var</span> field = <span class="built_in">document</span>.getElementById(<span class="string">"field"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 检测是否存在 autosave 键值</span></span><br><span class="line"><span class="comment">// (这个会在页面偶然被刷新的情况下存在)</span></span><br><span class="line"><span class="keyword">if</span> (sessionStorage.getItem(<span class="string">"autosave"</span>)) &#123;</span><br><span class="line">  <span class="comment">// 恢复文本输入框的内容</span></span><br><span class="line">  field.value = sessionStorage.getItem(<span class="string">"autosave"</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 监听文本输入框的 change 事件</span></span><br><span class="line">field.addEventListener(<span class="string">"change"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 保存结果到 sessionStorage 对象中</span></span><br><span class="line">  sessionStorage.setItem(<span class="string">"autosave"</span>, field.value)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>在兼容性和优点方面，sessionStorage和localStorage是差不多的，因此在此也就不多说了，下面我们来聊一聊IndexedDB。</p>
<h2 id="IndexedDB"><a href="#IndexedDB" class="headerlink" title="IndexedDB"></a>IndexedDB</h2><p>虽然web存储机制对于存储较少量的数据非常便捷好用，但对于存储更大量的结构化数据来说，这种方法就不太满足开发者们的需求了。IndexedDB就是为了应对这个需求而产生的，它是由HTML5所提供的一种本地存储，用于在浏览器中储存较大数据结构的 Web API，并提供索引功能以实现高性能查找。它一般用于保存大量用户数据并要求数据之间有搜索需要的场景，当网络断开时，用户就可以做一些离线的操作。它较之SQL更为方便，不需要写一些特定的语法对数据进行操作，数据格式是JSON。</p>
<h3 id="IndexedDB的基本语法"><a href="#IndexedDB的基本语法" class="headerlink" title="IndexedDB的基本语法"></a>IndexedDB的基本语法</h3><p>使用IndexedDB在浏览器端存储数据会比上述的其他方法更为复杂。首先，我们需要创建数据库，并指定这个数据库的版本号：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 注意数据库的版本号只能是整数</span></span><br><span class="line"><span class="keyword">const</span> request = IndexedDB.open(databasename, version)</span><br></pre></td></tr></table></figure></p>
<p>然后我们需要生成处理函数，需要注意的是onupgradeneeded 是我们唯一可以修改数据库结构的地方。在这里面，我们可以创建和删除对象存储空间以及构建和删除索引。<br>：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">request.onerror = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="comment">// 创建数据库失败时的回调函数</span></span><br><span class="line">&#125;</span><br><span class="line">request.onsuccess = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="comment">// 创建数据库成功时的回调函数</span></span><br><span class="line">&#125;</span><br><span class="line">request.onupgradeneededd = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">	 <span class="comment">// 当数据库改变时的回调函数</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后我们就可以建立对象存储空间了，对象存储空间仅调用 createObjectStore() 就可以创建。这个方法使用存储空间的名称，和一个对象参数。即便这个参数对象是可选的，它还是非常重要的，因为它可以让我们定义重要的可选属性和完善你希望创建的对象存储空间的类型。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">request.onupgradeneeded = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">const</span> db = event.target.result</span><br><span class="line">	<span class="keyword">const</span> objectStore = db.createObjectStore(<span class="string">'name'</span>, &#123; <span class="attr">keyPath</span>:<span class="string">'id'</span> &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对象的存储空间我们已经建立好了，接下来我们就可以进行一系列的骚操作了，比如来个蛇皮走位！不不不，口误口误，比如添加数据：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">addData: <span class="function"><span class="keyword">function</span>(<span class="params">db, storename, data</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">const</span> store = store = db.transaction(storename, <span class="string">'readwrite'</span>).objectStore(storename)</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; data.length; i++) &#123;</span><br><span class="line">		<span class="keyword">const</span> request = store.add(data[i])</span><br><span class="line">		request.onerror = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">			<span class="built_in">console</span>.error(<span class="string">'添加数据失败'</span>)</span><br><span class="line">		&#125;</span><br><span class="line">		request.onsuccess = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">			<span class="built_in">console</span>.log(<span class="string">'添加数据成功'</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果我们想要修改数据，语法与添加数据差不多，因为重复添加已存在的数据会更新原本的数据，但还是有细小的差别：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">putData: <span class="function"><span class="keyword">function</span>(<span class="params">db, storename, data</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">const</span> store = store = db.transaction(storename, <span class="string">'readwrite'</span>).objectStore(storename)</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; data.length; i++) &#123;</span><br><span class="line">		<span class="keyword">const</span> request = store.put(data[i])</span><br><span class="line">		request.onerror = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">			<span class="built_in">console</span>.error(<span class="string">'修改数据失败'</span>)</span><br><span class="line">		&#125;</span><br><span class="line">		request.onsuccess = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">			<span class="built_in">console</span>.log(<span class="string">'修改数据成功'</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>获取数据：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">getDataByKey: <span class="function"><span class="keyword">function</span>(<span class="params">db, storename, key</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">const</span> store = store = db.transaction(storename, <span class="string">'readwrite'</span>).objectStore(storename)</span><br><span class="line">	<span class="keyword">const</span> request = store.get(key)</span><br><span class="line">	request.onerror = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="built_in">console</span>.error(<span class="string">'获取数据失败'</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	request.onsuccess = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">const</span> result = e.target.result</span><br><span class="line">		<span class="built_in">console</span>.log(result)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>删除数据：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">deleteDate: <span class="function"><span class="keyword">function</span>(<span class="params">db, storename, key</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">const</span> store = store = db.transaction(storename, <span class="string">'readwrite'</span>).objectStore(storename)</span><br><span class="line">	store.delete(key)</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">'已删除存储空间'</span> + storename + <span class="string">'中的'</span> + key + <span class="string">'纪录'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>关闭数据库：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.close</span><br></pre></td></tr></table></figure>
<h3 id="IndexedDB的优点（相较于前面的存储方案）"><a href="#IndexedDB的优点（相较于前面的存储方案）" class="headerlink" title="IndexedDB的优点（相较于前面的存储方案）"></a>IndexedDB的优点（相较于前面的存储方案）</h3><ul>
<li>拥有更大的储存空间</li>
<li>能够处理更为复杂和结构化的数据</li>
<li>拥有更多的交互控制</li>
<li>每个’database’中可以拥有多个’database’和’table’</li>
</ul>
<h3 id="IndexedDB的局限性"><a href="#IndexedDB的局限性" class="headerlink" title="IndexedDB的局限性"></a>IndexedDB的局限性</h3><p>了解了IndexedDB的优点，我们当然也要来聊一聊IndexedDB的局限性与适用的场景：</p>
<h4 id="1-存储空间限制"><a href="#1-存储空间限制" class="headerlink" title="1. 存储空间限制"></a>1. 存储空间限制</h4><p>一个单独的数据库项目的大小没有限制。然而可能会限制每个 IndexedDB 数据库的大小。这个限制（以及用户界面对它进行断言的方式）在各个浏览器上也可能有所不同：</p>
<ul>
<li>Firefox: 对 IndexedDB 数据库的大小没有限制。在用户界面上只会针对存储超过 50 MB 大小的 BLOB（二进制大对象）请求权限。这个大小的限额可以通过 dom.indexedDB.warningQuota 首选项进行自定义。(定义在 <a href="http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/init/all.js)。" target="_blank" rel="noopener">http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/init/all.js)。</a></li>
<li>Google Chrome：<a href="https://developers.google.com/chrome...rage#temporary" target="_blank" rel="noopener">https://developers.google.com/chrome...rage#temporary</a><h4 id="2-兼容性问题"><a href="#2-兼容性问题" class="headerlink" title="2. 兼容性问题"></a>2. 兼容性问题</h4><img src="https://user-gold-cdn.xitu.io/2018/5/3/16325ce02ccb3e88?w=1240&amp;h=189&amp;f=png&amp;s=58377" alt="图片.png"><br>从上面的图我们可以看出对于IndexedDB的兼容来讲比前面所提及的存储方案要差不少，因此在使用IndexedDB时，我们也要好好的考虑兼容性的问题<h4 id="3-indexedDB受同源策略的限制"><a href="#3-indexedDB受同源策略的限制" class="headerlink" title="3. indexedDB受同源策略的限制"></a>3. indexedDB受同源策略的限制</h4>indexedDB使用同源原则，这意味着它把存储空间绑定到了创建它的站点的源（典型情况下，就是站点的域或是子域），所以它不能被任何其他源访问。要着重指出的一点是 IndexedDB 不适用于从另一个站点加载进框架的内容 (这是一项安全措施。详情请看这个：<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=595307" target="_blank" rel="noopener">https://bugzilla.mozilla.org/show_bug.cgi?id=595307</a></li>
</ul>
<p>除此之外，IndexedDB还存在诸如：不适合存储敏感数据，相较于web存储机制的操作更加复杂等问题，这都是我们在使用IndexedDB时需要考虑的。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/JavaScript/" rel="tag"># JavaScript</a>
          
            <a href="/blog/tags/浏览器/" rel="tag"># 浏览器</a>
          
            <a href="/blog/tags/数据存储/" rel="tag"># 数据存储</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/06/2.组件和元素/" rel="next" title="2.组件和元素">
                <i class="fa fa-chevron-left"></i> 2.组件和元素
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/11/从HTML5 WebSocket到Socket.io/" rel="prev" title="从HTML5 WebSocket到Socket.io">
                从HTML5 WebSocket到Socket.io <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言："><span class="nav-number">1.</span> <span class="nav-text">前言：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#浏览器存储"><span class="nav-number"></span> <span class="nav-text">浏览器存储</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cookie"><span class="nav-number"></span> <span class="nav-text">Cookie</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie的优点"><span class="nav-number">1.</span> <span class="nav-text">Cookie的优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie的缺点"><span class="nav-number">2.</span> <span class="nav-text">Cookie的缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie的操作"><span class="nav-number">3.</span> <span class="nav-text">Cookie的操作</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#web存储"><span class="nav-number"></span> <span class="nav-text">web存储</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#locaStorage"><span class="nav-number">1.</span> <span class="nav-text">locaStorage</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#localStorage的基本语法"><span class="nav-number">1.1.</span> <span class="nav-text">localStorage的基本语法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#localStorage储存数据的有效期与作用域"><span class="nav-number">1.2.</span> <span class="nav-text">localStorage储存数据的有效期与作用域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#localStorage的兼容"><span class="nav-number">1.3.</span> <span class="nav-text">localStorage的兼容</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sessionStorage"><span class="nav-number">2.</span> <span class="nav-text">sessionStorage</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#sessionStorage的基本语法"><span class="nav-number">2.1.</span> <span class="nav-text">sessionStorage的基本语法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#IndexedDB"><span class="nav-number"></span> <span class="nav-text">IndexedDB</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#IndexedDB的基本语法"><span class="nav-number">1.</span> <span class="nav-text">IndexedDB的基本语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IndexedDB的优点（相较于前面的存储方案）"><span class="nav-number">2.</span> <span class="nav-text">IndexedDB的优点（相较于前面的存储方案）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IndexedDB的局限性"><span class="nav-number">3.</span> <span class="nav-text">IndexedDB的局限性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-存储空间限制"><span class="nav-number">3.1.</span> <span class="nav-text">1. 存储空间限制</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-兼容性问题"><span class="nav-number">3.2.</span> <span class="nav-text">2. 兼容性问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-indexedDB受同源策略的限制"><span class="nav-number">3.3.</span> <span class="nav-text">3. indexedDB受同源策略的限制</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
